
import sys
import json

from .data import testsuite_format
from .parse import parse
from .elements import e
from .globals import g
from .windows import w
from .testsuite import TestSuite
from .log import logger
from .junit import JUnit
from . import data_tool


class Autotest:
    def __init__(self, autotest_data, task_data: dict, selenium_session=None):
        self.selenium_session = selenium_session
        self.element_define = autotest_data['element']
        self.test_case_define = autotest_data['case']
        self.step_define = autotest_data['step']
        g.var = autotest_data['testdata_define']  # 测试数据
        g.sid = str(autotest_data['sid'])  # tdp集成新增
        g.task_data = task_data  # tdp集成新增
        g.tdp_server_addr = str(autotest_data['tdp_server_addr'])  # tdp集成新增
        g.tdp_token = str(autotest_data['tdp_token'])  # tdp集成新增，等于测试任务ID，用于标识测试任务
        g.task_id = str(autotest_data['task_id'])  # tdp集成新增，等于测试任务ID，用于标识测试任务
        g.result_set_id = str(autotest_data['result_set_id'])  # tdp集成新增，测试结果ID，用于保存测试日志

        d = data_tool.deal_with_source_data(
            case_dlist=self.test_case_define,
            step_dlist=self.step_define,
            element_dlist=self.element_define,
        )
        self.case = d['case']

        self.desired_caps = {
            'platformName': 'Desktop',
            'browserName': 'Chrome',
            'element_wait_timeout': 5,
            'page_flash_timeout': 90
        }
        self.desired_caps.update(autotest_data['exec_config'])
        self.desired_caps['appConfig'] = json.loads(self.desired_caps.get('appConfig', '{}'))
        g.element_wait_timeout = int(self.desired_caps['findElementTimeout'])
        g.page_flash_timeout = int(self.desired_caps.get('pageLoadTimeout', 20))
        self.server_url = ''
        self.conditions = {}
        g.plan_name = g.task_id
            
        self.report_data = {}  # 测试报告详细数据

    def fliter(self, **kwargs):
        # 筛选要执行的测试用例
        self.conditions = kwargs

    def plan(self):
        self.code = 0  # 返回码
        # 1.解析配置文件
        try:
            e.get_elements(self.element_define)
        except:
            logger.exception('*** Parse config file failure ***')
            self.code = -1
            sys.exit(self.code)

        self.junit = JUnit()
        self.junit_suite = {}

        # 2.逐个执行测试套件
        g.sheet_name = g.task_id
        # xml 测试报告初始化
        # self.junit_suite[g.task_id] = self.junit.create_suite(
        #     g.plan_name, g.task_id)
        # self.junit_suite[g.task_id].start()
        self.run()

    def run(self):
        # 1.从 Excel 获取测试用例集
        try:
            testsuite = testsuite_format(self.case)
            logger.info('load testsuite data success')
        except:
            logger.exception('*** load testsuite data failure ***')
            self.code = -1
            sys.exit(self.code)

        # 2.初始化全局对象
        try:
            g.init(self.desired_caps, self.server_url)
            g.set_driver()
            w.init()
        except:
            logger.exception('*** Init global object failure ***')
            self.code = -1
            sys.exit(self.code)

        # 3.解析测试用例集
        try:
            parse(testsuite)
            logger.debug('testsuite has been parsed:\n' + str(testsuite))
        except:
            logger.exception('*** Parse testsuite failure ***')
            self.code = -1
            sys.exit(self.code)

        # 4.执行测试套件
        ts = TestSuite(testsuite, g.task_id, self.conditions)
        ts.run()

        g.driver.quit()

        logger.info("--- 执行结束 ---")



